import { computed, onMounted, ref } from "vue";

// 封装分页加载的 Hook
function usePagination(fetchData, options = {}) {
	const {
		initialLoad = true
	} = options;
	// 当前页码
	const currentPage = ref(1);
	// 每页条数
	const pageSize = ref(10);
	// 数据列表
	const dataList = ref([]);
	// 是否正在加载
	const isLoading = ref(false);
	// 是否还有更多数据
	const hasMore = ref(true);
	// 是否为空
	const isEmpty = computed(() => !dataList.value.length &&  !isLoading.value && !hasMore.value);
	// 加载更多状态
	const loadMoreStatus = computed(() => isLoading.value ? 'loading' : hasMore.value ? 'loadmore' : 'nomore' );

	// 加载数据的函数
	const loadData = async () => {
		if (isLoading.value || !hasMore.value) return;
		isLoading.value = true;
		try {
			// 调用传入的获取数据的函数
			const response = await fetchData(currentPage.value, pageSize.value);
			const newData = response.data;
			if (newData.length < pageSize.value) {
				hasMore.value = false;
			}
			if(currentPage.value === 1){
				dataList.value = [];
			}
			dataList.value = [...dataList.value, ...newData];
			currentPage.value++;
		} catch (error) {
			console.error('加载数据失败:', error);
		} finally {
			isLoading.value = false;
		}
	};

	// 加载更多数据
	const loadMore = () => {
		loadData();
	};

	// 初始化加载数据
	const initialLoadData = () => {
		if (initialLoad) return;
		loadData();
	};

	if (initialLoad) {
		onMounted(() => {
			loadData();
		});
	}

	return {
		dataList,
		isLoading,
		hasMore,
		loadMore,
		isEmpty,
		loadMoreStatus,
		initialLoadData
	};
}

export default usePagination;